package com.e1xp.deport_management_system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.e1xp.deport_management_system.entity.User;
import com.e1xp.deport_management_system.exception.CustomException;
import com.e1xp.deport_management_system.exception.CustomExceptionType;
import com.e1xp.deport_management_system.mapper.UserMapper;
import com.e1xp.deport_management_system.service.IUserService;
import com.e1xp.deport_management_system.utils.MD5;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author E1xP
 * @since 2021-04-09
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    UserMapper userMapper;

    /**
     * 用于获取用户名对应的用户实体
     * @param username 用户名
     * @param password 用户密码
     * @param timestamp 时间戳
     * @return User对应的实体类
     * @throws CustomException 当用户名与密码不匹配时抛出该异常
     */
    @Override
    public User login(String username, String password, long timestamp) throws CustomException {
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",username);
        User user=userMapper.selectOne(queryWrapper);
        if(user==null){
            throw new CustomException(CustomExceptionType.USER_LOGIN_ERROR);
        }else{
            if(!MD5.md5L32("depot" + user.getPassword() + "repo" + timestamp).equals(password)){
                throw new CustomException(CustomExceptionType.USER_LOGIN_ERROR);
            }
        }
        return user;
    }

    /**
     * 添加用户
     * @param username 用户名
     * @param password 用户密码
     * @param type 用户类型
     * @return User 添加后的用户实体类
     */
    @Override
    public User add(String username, String password, int type, long instanceId) {
        User user=new User(null,username,password,type,instanceId);
        userMapper.insert(user);
        return user;
    }

    /**
     * 通过用户id获取用户实体
     *
     * @param userId 用户id
     * @return User 用户实体类
     */
    User get(long userId) {
        return userMapper.selectById(userId);
    }

    /**
     * 通过用户id与实例id获取用户实体
     *
     * @param instanceId 实例id
     * @param userId     用户id
     * @return User 用户实体类
     */
    @Override
    public User get(long instanceId, long userId) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("instance_id", instanceId)
                .eq("id", userId);
        return userMapper.selectOne(queryWrapper);
    }

    /**
     * 用于修改用户类型
     *
     * @param instanceId 实例id
     * @param id         用户id
     * @param type       修改用户类型
     * @throws CustomException 当用户不存在，用户类型不合法是抛出该异常
     */
    @Override
    public void changeType(long instanceId, long id, int type) throws CustomException {
        User user = get(instanceId, id);
        if (user == null) {
            //用户不存在
            throw new CustomException(CustomExceptionType.USER_NOT_FOUND_ERROR, "找不到该用户");
        }
        if (type < 0 || type > 1) {
            //状态不合法
            throw new CustomException(CustomExceptionType.USER_INPUT_ERROR, "不存在该用户类型");
        }
        user.setType(type);
        userMapper.updateById(user);
    }

    /**
     * 用于修改用户密码
     *
     * @param instanceId 实例id
     * @param id         用户id
     * @param password   修改密码
     * @throws CustomException 当用户不存在时抛出该异常
     */
    @Override
    public void changePasswordFromAdmin(long instanceId, long id, String password) throws CustomException {
        User user = get(instanceId, id);
        if (user == null) {
            //用户不存在
            throw new CustomException(CustomExceptionType.USER_NOT_FOUND_ERROR, "找不到该用户");
        }
        user.setPassword(password);
        userMapper.updateById(user);
    }

    /**
     * 用于修改密码
     *
     * @param userId      用户id
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @throws CustomException 当用户输入旧密码与旧密码不匹配时抛出该异常
     */
    @Override
    public void changePassword(long userId, String oldPassword, String newPassword) throws CustomException {
        User user=userMapper.selectById(userId);
        if(user==null){
            throw new CustomException(CustomExceptionType.USER_NOT_FOUND_ERROR,"找不到该用户");
        }
        if(user.getPassword().equals(oldPassword)){
            user.setPassword(newPassword);
            userMapper.updateById(user);
        }else{
            throw new CustomException("旧密码错误", 400);
        }
    }

    /**
     * 用于检查是否是实例
     *
     * @param instanceId 实例id
     * @return 是否存在该实例
     */
    public boolean isInstance(long instanceId) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("instance_id", instanceId);
        return userMapper.selectCount(queryWrapper) > 0;
    }

    /**
     * 用于添加新实例
     *
     * @param user 用户实体
     */
    @Override
    public void addInstance(User user) throws CustomException {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user.getUsername());
        if (userMapper.selectCount(queryWrapper) > 0) {
            //已存在同名用户名
            throw new CustomException(CustomExceptionType.USER_INPUT_ERROR, "用户名已存在，请更换后再试");
        }
        user.setType(0);
        user.setInstanceId(userMapper.getMaxInstanceId() + 1);
        userMapper.insert(user);
    }

    /**
     * 用于获取用户列表（不返还密码
     *
     * @param instanceId 实例id
     * @return List User列表
     */
    @Override
    public List<User> getList(long instanceId) {
        return userMapper.getList(instanceId);
    }

    /**
     * 用于停用账户
     *
     * @param instanceId 实例id
     * @param userId     停用用户id
     * @throws CustomException 当无对应用户，账户已停用时抛出该异常
     */
    @Override
    public void suspendUser(long instanceId, long userId) throws CustomException {
        User user = get(instanceId,userId);
        if (user == null) {
            //无对应用户
            throw new CustomException(CustomExceptionType.USER_NOT_FOUND_ERROR, "该用户不存在");
        }
        if (user.getType() < 0 || user.getType() > 1) {
            //已停用，不允许操作
            throw new CustomException(CustomExceptionType.OPERATION_NOT_ALLOW, "账户已停用，请勿重复停用");
        }
        user.setType(user.getType() - 2);
        userMapper.updateById(user);
    }

    /**
     * 用于启用用户
     *
     * @param instanceId 实例id
     * @param userId     用户id
     * @throws CustomException 当用户不存在，用户已启用时抛出该异常
     */
    @Override
    public void activeUser(long instanceId, long userId) throws CustomException {
        User user = get(instanceId, userId);
        if (user == null) {
            //用户不存在
            throw new CustomException(CustomExceptionType.USER_NOT_FOUND_ERROR, "找不到该用户");
        }
        if (user.getType() < -2 || user.getType() > -1) {
            //用户已启用
            throw new CustomException(CustomExceptionType.OPERATION_NOT_ALLOW, "用户已启用");
        }
        user.setType(user.getType() + 2);
        userMapper.updateById(user);
    }
}
